package com.ruoyi.system.service.college.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.college.Statistics.PrizeVO;
import com.ruoyi.system.domain.college.Statistics.TeamVO;
import com.ruoyi.system.domain.college.Statistics.UniversityStatDTO;
import com.ruoyi.system.domain.teacher.Statistics.TeacherStatisticsRequestVO;
import com.ruoyi.system.domain.teacher.UserEducation;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.award.competition.CompetitionAwardInfoMapper;
import com.ruoyi.system.mapper.award.party.PartyAwardInfoMapper;
import com.ruoyi.system.mapper.award.research.ResearchAwardInfoMapper;
import com.ruoyi.system.mapper.award.teach.TeachAwardInfoMapper;
import com.ruoyi.system.mapper.honor.PersonalHonorMapper;
import com.ruoyi.system.mapper.honor.TeamHonorMapper;
import com.ruoyi.system.mapper.project.BookMapper;
import com.ruoyi.system.mapper.project.PaperInfoMapper;
import com.ruoyi.system.mapper.project.PatentMapper;
import com.ruoyi.system.mapper.teacher.UserEducationMapper;
import com.ruoyi.system.service.college.ICollegeStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 学院统计im pl
 * @Author: liuwei
 * @Date: 2020/2/27
 * @Version V1.0
 */
@Service
public class ICollegeStatisticsServiceImpl implements ICollegeStatisticsService {
    // 用户信息
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private UserEducationMapper userEducationMapper;// 用户学历
    @Autowired
    private ResearchAwardInfoMapper researchAwardInfoMapper;//科研获奖信息
    @Autowired
    private TeachAwardInfoMapper teachAwardInfoMapper;//教学获奖信息
    @Autowired
    private PersonalHonorMapper personalHonorMapper;//个人荣誉信息
    @Autowired
    private TeamHonorMapper teamHonorMapper;//团队荣誉信息
    @Autowired
    private BookMapper bookMapper;//书籍信息
    @Autowired
    private PaperInfoMapper paperInfoMapper;//论文信息
    @Autowired
    private PatentMapper patentMapper;//专利信息
    @Autowired
    private PartyAwardInfoMapper partyAwardInfoMapper;//党建获奖信息
    @Autowired
    private CompetitionAwardInfoMapper competitionAwardInfoMapper;//竞赛获奖信息
    /**
     * 获取学院统计信息（底部信息）
     * @param requestVO
     * @return
     */
    @Override
    public PrizeVO getList(TeacherStatisticsRequestVO requestVO) {
        // 2. 调用各mapper查询对应数据（假设各mapper已实现按用户ID和年份统计的方法）
        String year = requestVO.getYear();

        int researchAwardCount =0;//科研获奖信息
        int personalHonorCount =0;//个人荣誉信息
        int bookCount = 0;//书籍信息
        int paperCount =0;//论文信息
        int teachAwardCount = 0;//教学获奖信息
        int patentCount =0;//专利信息
        int competitionCount=0;   //竞赛获奖信息
        int teamHonorCount =0;//
        int partyCount = 0;//

        if(year!=null&&year.equals("2020之前")){
              researchAwardCount = researchAwardInfoMapper.countByUserIdAndYearBefore(null );//科研获奖信息
              personalHonorCount = personalHonorMapper.countByUserIdAndYearBefore(null );//个人荣誉信息
              bookCount = bookMapper.countByUserIdAndYearBefore(null );//书籍信息
              paperCount = paperInfoMapper.countByUserIdAndYearBefore(null );//论文信息
              teachAwardCount = teachAwardInfoMapper.countByUserIdAndYearBefore(null );//教学获奖信息
              //patentCount = patentMapper.countByUserIdAndYearBefore(null );//专利信息
              competitionCount=competitionAwardInfoMapper.countByUserIdAndYearBefore(null );   //竞赛获奖信息
              //teamHonorCount = teamHonorMapper.countByUserIdAndYearBefore(null );//
              //partyCount = partyAwardInfoMapper.getCountByYear( year);//
        }else{
              researchAwardCount = researchAwardInfoMapper.countByUserIdAndYear(null, year);//科研获奖信息
              personalHonorCount = personalHonorMapper.countByUserIdAndYear(null,year);//个人荣誉信息
              bookCount = bookMapper.countByUserIdAndYear(null, year);//书籍信息
              paperCount = paperInfoMapper.countByUserIdAndYear(null, year);//论文信息
              teachAwardCount = teachAwardInfoMapper.countByUserIdAndYear(null, year);//教学获奖信息
              patentCount = patentMapper.countByUserIdAndYear(null, year);//专利信息
              competitionCount=competitionAwardInfoMapper.countByUserIdAndYear(null, year);   //竞赛获奖信息
              teamHonorCount = teamHonorMapper.countByDeptIdAndYear(null, year);//
              partyCount = partyAwardInfoMapper.getCountByYear( year);//
        }


        PrizeVO ra = new PrizeVO();
        ra.setResearch(String.valueOf(researchAwardCount));
        ra.setPersonHoner(String.valueOf(personalHonorCount));
        ra.setBook(String.valueOf(bookCount));
        ra.setPaper(String.valueOf(paperCount));
        ra.setTeach(String.valueOf(teachAwardCount));
        ra.setPatent(String.valueOf(patentCount));
        ra.setCompetition(String.valueOf(competitionCount));
        ra.setTeamCount(String.valueOf(teamHonorCount));
        ra.setParty(String.valueOf(partyCount));

        return ra;
    }
    /**
     * 统计团队情况
     * @return
     */
    @Override
    public List<TeamVO> statisticTeam() {
        // 1. 创建三个统计对象：正高级、副高级、其他
        TeamVO senior = new TeamVO("正高级");
        TeamVO associate = new TeamVO("副高级");
        TeamVO other = new TeamVO("其他");

        // 2. 获取所有教师
        List<SysUser> teachers = userMapper.findAll();

        // 3. 遍历教师，统计数据
        for (SysUser teacher : teachers) {
            // 计算年龄
            int age = calculateAge(teacher.getBirthday());

            // 根据职称选择对应的统计对象
            TeamVO statistic = getStatisticByTitle(teacher.getProfessionalTitle(), senior, associate, other);

            // 总人数+1
            statistic.setTotal(statistic.getTotal() + 1);

            // 按年龄段统计
            if (age <= 35) {
                statistic.setAge35Below(statistic.getAge35Below() + 1);
            } else if (age <= 45) {
                statistic.setAge36To45(statistic.getAge36To45() + 1);
            } else if (age <= 55) {
                statistic.setAge46To55(statistic.getAge46To55() + 1);
            } else if (age <= 60) {
                statistic.setAge56To60(statistic.getAge56To60() + 1);
            } else {
                statistic.setAge61Above(statistic.getAge61Above() + 1);
            }
            //1硕士 2博士 3博导 4硕导 5其他
            // 博士统计
            if(teacher.getTeacherTitle()!= null){
                if (teacher.getTeacherTitle().equals("2")) {
                    statistic.setPhdCount(statistic.getPhdCount() + 1);
                }

                // 博导统计
                if (teacher.getTeacherTitle().equals("3")) {
                    statistic.setPhdAdvisor(statistic.getPhdAdvisor() + 1);
                }

                // 硕导统计
                if (teacher.getTeacherTitle().equals("4")) {
                    statistic.setMasterAdvisor(statistic.getMasterAdvisor() + 1);
                }
            }
        }

        // 4. 计算总计行
        TeamVO total = calculateTotal(senior, associate, other);

        // 5. 组装结果列表
        List<TeamVO> result = new ArrayList<>();
        result.add(senior);
        result.add(associate);
        result.add(other);
        result.add(total);

        return result;
    }
    /**
     * 根据传入的部门id查询有多少人 以及系年度得奖总数量
     *
     * @return
     */
    @Override
    public PrizeVO statisticPerson(TeacherStatisticsRequestVO requestVO) {
        int countTeacher = userMapper.selectCountByDeptId(Long.valueOf(requestVO.getDeptId()) );
        // 2. 调用各mapper查询对应数据（假设各mapper已实现按用户ID和年份统计的方法）
        int teachAwardCount = teachAwardInfoMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//教学获奖信息
        int competitionCount=competitionAwardInfoMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//竞赛获奖信息
        int researchAwardCount = researchAwardInfoMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//科研获奖信息
        int personalHonorCount = personalHonorMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//个人荣誉信息
        int bookCount = bookMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//书籍信息
        int patentCount = 0;//专利信息
        int paperCount = paperInfoMapper.countByDeptIdAndYear(requestVO.getDeptId(), requestVO.getYear());//论文信息
        int partyCount =0;//党建获奖信息
        int teamCount = 0;//团队荣誉信息
        PrizeVO ra = new PrizeVO();
        ra.setTeacherCount(String.valueOf(countTeacher));
        ra.setTeamCount(String.valueOf(patentCount+teachAwardCount+competitionCount+researchAwardCount+teamCount+paperCount+bookCount+personalHonorCount+ partyCount));
        return ra;
    }

    /**
     * 统计学历分布
     * @return
     */
    @Override
    public List<UniversityStatDTO> statisticEducation() {
        // 1. 获取所有教师的最高学历信息
        List<UserEducation> highestEducations = userEducationMapper.selectHighestEducationForEachTeacher();

        if (CollectionUtils.isEmpty(highestEducations)) {
            return null;
        }

        // 2. 按学校分组统计人数
        Map<String, Long> universityCountMap = highestEducations.stream()
                .collect(Collectors.groupingBy(UserEducation::getSchool, Collectors.counting()));

        // 3. 计算总人数
        long total = highestEducations.size();

        // 4. 转换为DTO并排序取前5
        List<UniversityStatDTO> topUnits = universityCountMap.entrySet().stream()
                .map(entry -> {
                    UniversityStatDTO dto = new UniversityStatDTO();
                    dto.setName(entry.getKey());
                    dto.setCount(entry.getValue().intValue());
                    // 计算百分比，保留一位小数
                    double percent = (entry.getValue() * 100.0) / total;
                    dto.setPercentage(String.format("%.1f%%", percent));
                    return dto;
                })
                .sorted((a, b) -> Integer.compare(b.getCount(), a.getCount())) // 降序排序
                .limit(5) // 取前5
                .collect(Collectors.toList());

        return topUnits;
    }
    /**
     * 获取学院首页信息
     * @param requestVO
     * @return
     */
    @Override
    public String getIndexInfo(TeacherStatisticsRequestVO requestVO) {
        return "";
    }

    // 计算年龄
    private int calculateAge(Date birthday) {
        if (birthday == null) {
            return 0; // 处理生日为空的情况
        }

        // 将java.util.Date转换为java.time.LocalDate
        LocalDate birthDate = birthday.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 计算年龄
        return Period.between(birthDate, LocalDate.now()).getYears();
    }
    // 根据职称获取对应的统计对象//1正高级 2副高级 3其他
    private TeamVO getStatisticByTitle(String title,
                                       TeamVO senior,
                                       TeamVO associate,
                                       TeamVO other) {
        if ("1".equals(title)) {
            return senior;
        } else if ("2".equals(title)) {
            return associate;
        } else {
            return other;
        }
    }

    // 计算总计行
    private TeamVO calculateTotal(TeamVO... statistics) {
        TeamVO total = new TeamVO("总计");
        for (TeamVO stat : statistics) {
            total.setTotal(total.getTotal() + stat.getTotal());
            total.setAge35Below(total.getAge35Below() + stat.getAge35Below());
            total.setAge36To45(total.getAge36To45() + stat.getAge36To45());
            total.setAge46To55(total.getAge46To55() + stat.getAge46To55());
            total.setAge56To60(total.getAge56To60() + stat.getAge56To60());
            total.setAge61Above(total.getAge61Above() + stat.getAge61Above());
            total.setPhdCount(total.getPhdCount() + stat.getPhdCount());
            total.setPhdAdvisor(total.getPhdAdvisor() + stat.getPhdAdvisor());
            total.setMasterAdvisor(total.getMasterAdvisor() + stat.getMasterAdvisor());
        }
        return total;
    }


    /**
     * 获取学院总览信息 教师人数 荣誉总数
     * @param requestVO
     * @return
     */
    @Override
    public PrizeVO overview(TeacherStatisticsRequestVO requestVO) {
        //和教师数量 除开逻辑删除admin
        int teacherCount = userMapper.getTeacherCount();//获取教师数量
        int teamHonorCount = teamHonorMapper.getCountByYear(requestVO.getYear());//获取团队荣誉数量
       // int partyCount = partyAwardInfoMapper.getCountByYear(requestVO.getYear());//获取党建获奖数量

        PrizeVO prizeVO = new PrizeVO();
        prizeVO.setTeacherCount(String.valueOf(teacherCount));
        prizeVO.setTeamCount(String.valueOf(teamHonorCount ));//团队荣誉和党建数量 =  院团队获奖数

        return prizeVO;
    }

}
